package com.xh.shuati.manager;
import cn.hutool.core.collection.CollUtil;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionChoice;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import com.xh.shuati.common.ErrorCode;
import com.xh.shuati.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/***
 * 通用的 AI 调用类
 */
@Service
public class AiManager {

    @Resource
    private ArkService arkService;

    private  static final String DEFAULT_MODEL = "deepseek-v3-250324";
    private  static final String DEFAULT_SYSTEM_PROMPT = "你是一个助手，请根据用户输入，给出一个最合适的答案";


    /***
     * 调用AI接口，获取相应字符串
     * @param userPrompt
     * @return
     */
    public String doChat(String systemPrompt,String userPrompt){
        //构造消息列表
        final List messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(userPrompt).build();
        messages.add(systemMessage);
        messages.add(userMessage);

        //构造请求
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
                .model(DEFAULT_MODEL)
                .messages(messages)
                .build();
        //发生请求
        List<ChatCompletionChoice> choices = arkService.createChatCompletion(chatCompletionRequest).getChoices();
        if(CollUtil.isNotEmpty( choices)){
            return (String)  choices.get(0).getMessage().getContent();
        }
        throw new BusinessException( ErrorCode.OPERATION_ERROR, "AI调用失败，没有返回结果");
        //关闭链接
//        arkService.shutdownExecutor();
    }


    /***
     * 调用AI接口，获取相应字符串
     * @param userPrompt
     * @return
     */
    public String doChat(String userPrompt){
        return  doChat(DEFAULT_SYSTEM_PROMPT,userPrompt);
    }
}
